<?php
declare (strict_types = 1);

namespace app\controller;

use app\middleware\Auth;
use app\model\Note;
use app\model\NoteDraw;
use app\model\SystemSetting;
use app\model\User;
use think\facade\Db;
use think\Request;
use EasyWeChat\Factory;
use think\facade\Env;
use think\exception\ValidateException;

/**
 * 纸条控制器
 * @OA\Tag(name="纸条", description="纸条提交与抽取")
 */
class NoteController extends ApiBaseController
{
    /**
     * 前置中间件
     * @var arraypublic function index(Request $request)
     */
    protected $middleware = [
        Auth::class, // 暂时注释掉全局Auth，因为submit和draw前已有checkLogin
    ];
    
    /**
     * 提交纸条
     *
     * @OA\Post(
     *     path="/api/note/submit",
     *     summary="提交纸条",
     *     description="提交个人纸条信息到系统",
     *     tags={"纸条"},
     *     security={{"bearerAuth":{}}},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"nickname", "gender", "age", "city", "wechat_id"},
     *                 @OA\Property(property="nickname", type="string", example="张三", description="昵称"),
     *                 @OA\Property(property="avatar", type="string", example="https://example.com/avatar.jpg", description="头像地址URL"),
     *                 @OA\Property(property="gender", type="integer", enum={0, 1, 2}, example=1, description="性别: 0-未知, 1-男, 2-女"),
     *                 @OA\Property(property="age", type="integer", example=25, description="年龄"),
     *                 @OA\Property(property="city", type="string", example="北京", description="城市"),
     *                 @OA\Property(property="wechat_id", type="string", example="wxid_123456", description="微信号码"),
     *                 @OA\Property(property="wechat_qrcode", type="string", example="https://example.com/qrcode.jpg", description="微信二维码图片URL")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="提交成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="提交纸条成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="id", type="integer", example=1, description="纸条ID")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="msg", type="string", example="昵称不能为空"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function submit(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        try {
            // 验证参数
            $param = $request->post();
            
            // 验证字段
            $validate = $this->validate($param, [
                'nickname' => 'require|max:50',
                'gender' => 'require|in:0,1,2',
                'age' => 'require|number|between:1,150',
                'city' => 'require|max:50',
                'avatar' => 'url|max:255',
                'wechat_id' => 'max:100',
                'wechat_qrcode' => 'url|max:255',
            ], [
                'nickname.require' => '昵称不能为空',
                'nickname.max' => '昵称长度不能超过50个字符',
                'gender.require' => '性别不能为空',
                'gender.in' => '性别参数错误',
                'age.require' => '年龄不能为空',
                'age.number' => '年龄必须是数字',
                'age.between' => '年龄范围必须在1-150之间',
                'city.require' => '城市不能为空',
                'city.max' => '城市长度不能超过50个字符',
                'avatar.url' => '头像地址格式不正确',
                'avatar.max' => '头像地址过长',
                'wechat_id.max' => '微信号过长',
                'wechat_qrcode.url' => '微信二维码地址格式不正确',
                'wechat_qrcode.max' => '微信二维码地址过长',
            ]);
            
            if ($validate !== true && is_string($validate)) {
                return $this->error($validate);
            }
            
            // 创建纸条
            $note = Note::create([
                'user_id'       => $this->user->id,
                'avatar'        => $param['avatar'] ?? $this->user->avatar ?? '',
                'nickname'      => $param['nickname'],
                'gender'        => $param['gender'],
                'age'           => $param['age'],
                'city'          => $param['city'],
                'wechat_id'     => $param['wechat_id'] ?? '',
                'wechat_qrcode' => $param['wechat_qrcode'] ?? '',
                'status'        => 1, // 1:未抽取
            ]);
            
            if (!$note) {
                return $this->error('提交纸条失败');
            }
            
            return $this->success(['id' => $note->id], '提交纸条成功');
            
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        } catch (\Exception $e) {
            \think\facade\Log::error('Submit note failed: ' . $e->getMessage() . ' Trace: ' . $e->getTraceAsString());
            return $this->error('提交纸条时发生内部错误');
        }
    }
    
    /**
     * 抽取纸条
     *
     * @OA\Post(
     *     path="/api/note/draw",
     *     summary="抽取纸条",
     *     description="根据条件随机抽取纸条，支持单抽和多抽",
     *     tags={"纸条"},
     *     security={{"bearerAuth":{}}},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"count"},
     *             @OA\Property(property="count", type="integer", example=1, description="抽取数量"),
     *             @OA\Property(property="gender", type="integer", enum={0, 1, 2}, example=1, description="性别筛选: 0-未知, 1-男, 2-女"),
     *             @OA\Property(property="min_age", type="integer", example=18, description="最小年龄"),
     *             @OA\Property(property="max_age", type="integer", example=30, description="最大年龄"),
     *             @OA\Property(property="city", type="string", example="上海", description="城市筛选")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="创建抽取订单成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="创建抽取订单成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="order_id", type="string", example="ND2023071512345678", description="订单号"),
     *                 @OA\Property(property="amount", type="number", format="float", example=1.00, description="支付金额"),
     *                 @OA\Property(property="count", type="integer", example=1, description="抽取数量"),
     *                 @OA\Property(property="payment", type="object", description="微信支付参数")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数错误或抽取失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="msg", type="string", example="没有符合条件的纸条"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function draw(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        try {
            // 验证参数
            $param = $request->post();
            $validate = $this->validate($param, [
                'count' => 'require|number|min:1',
                'gender' => 'in:0,1,2',
                'min_age' => 'number|min:1',
                'max_age' => 'number|egt:min_age',
                'city' => 'max:50',
            ], [
                'count.require' => '抽取数量不能为空',
                'count.number' => '抽取数量必须是数字',
                'count.min' => '抽取数量必须大于0',
                'gender.in' => '性别参数错误',
                'min_age.number' => '最小年龄必须是数字',
                'min_age.min' => '最小年龄必须大于0',
                'max_age.number' => '最大年龄必须是数字',
                'max_age.egt' => '最大年龄必须大于或等于最小年龄',
                'city.max' => '城市长度不能超过50个字符',
            ]);
            
            if ($validate !== true && is_string($validate)) {
                return $this->error($validate);
            }
            
            // 获取抽取参数
            $count = (int) $param['count'];
            $gender = isset($param['gender']) && $param['gender'] !== '' ? (int) $param['gender'] : null;
            $minAge = isset($param['min_age']) && $param['min_age'] !== '' ? (int) $param['min_age'] : null;
            $maxAge = isset($param['max_age']) && $param['max_age'] !== '' ? (int) $param['max_age'] : null;
            $city = $param['city'] ?? null;
            
            // 获取纸条单价
            $price = SystemSetting::getNotePrice();
            if ($price <= 0) {
//                $price = 1; // 假设默认1元
                \think\facade\Log::warning('Note price setting is invalid or zero, using default.');
            }
            $totalAmount = $price * $count;
            
            // 开始事务
            // Db::startTrans(); // 使用 Db::transaction 替代手动事务
            try {
                // 使用闭包进行查询和锁定，避免并发问题
                $notes = Db::transaction(function () use ($count, $gender, $minAge, $maxAge, $city) {
                    $query = Note::where('status', 1)
                        ->where('user_id', '<>', $this->user->id);
                    
                    if ($gender !== null) {
                        $query->where('gender', $gender);
                    }
                    if ($minAge !== null) {
                        $query->where('age', '>=', $minAge);
                    }
                    if ($maxAge !== null) {
                        $query->where('age', '<=', $maxAge);
                    }
                    if ($city !== null && $city !== '') {
                        $query->where('city', 'like', '%' . $city . '%');
                    }
                    
                    // 在事务内再次检查数量并锁定行 (如果数据库支持)
                    // 注意：RAND() 可能在锁定或事务中表现不佳，取决于数据库
                    // 如果遇到性能问题，考虑先获取ID，再根据ID查询并锁定
                    $notesToDraw = $query->lock(true)->orderRaw('RAND()')->limit($count)->select();
                    if (count($notesToDraw) < $count) {
                        // 如果在锁定后发现纸条不足，抛出异常回滚事务
                        $availableCount = Note::where('status', 1)
                            ->where('user_id', '<>', $this->user->id);
                        if ($gender !== null) $availableCount->where('gender', $gender);
                        if ($minAge !== null) $availableCount->where('age', '>=', $minAge);
                        if ($maxAge !== null) $availableCount->where('age', '<=', $maxAge);
                        if ($city !== null && $city !== '') $availableCount->where('city', 'like', '%' . $city . '%');
                        $currentAvailable = $availableCount->count();
                        throw new \Exception("符合条件的纸条不足，仅剩 {$currentAvailable} 张", 400);
                    }
                    return $notesToDraw;
                });
                
                // 生成订单号
                $orderId = 'ND' . date('YmdHis') . mt_rand(1000, 9999);
                
                // 创建抽取记录 (在事务成功后创建或更新状态)
                $noteDraw = NoteDraw::create([
                    'user_id' => $this->user->id,
                    'note_id' => isset($notes[0]) ? $notes[0]->id : 0, // 总是使用第一个纸条ID，或在没有纸条时使用0
                    'order_id' => $orderId,
                    'draw_type' => $count > 1 ? 2 : 1,
                    'draw_count' => $count,
                    'amount' => $totalAmount,
                    'status' => 0, // 初始为未支付
                ]);
                
                if (!$noteDraw) {
                    // 如果创建失败（理论上不太可能在事务外）
                    throw new \Exception('创建抽取记录失败', 500);
                }
                
                // 如果是多抽，创建抽取纸条关联记录 (也在事务成功后进行)
                if ($count > 1) {
                    $drawItems = [];
                    $now = date('Y-m-d H:i:s');
                    foreach ($notes as $note) {
                        $drawItems[] = [
                            'draw_id' => $noteDraw->id,
                            'note_id' => $note->id,
                            'create_time' => $now
                        ];
                    }
                    if (!empty($drawItems)) {
                        // 修改为更可靠的批量添加方式
                        Db::name('note_draw_items')->insertAll($drawItems);
                    }
                }
                
                // 生成微信支付订单（现在事务已成功）
                $paymentParams = $this->createWechatPayment($noteDraw);
                
                // 事务提交已由 Db::transaction 自动处理
                
                return $this->success([
                    'order_id' => $orderId,
                    'amount' => $totalAmount,
                    'count' => $count,
                    'payment' => $paymentParams
                ], '创建抽取订单成功');
                
            } catch (\Exception $e) {
                // Db::rollback(); // Db::transaction 失败时会自动回滚
                \think\facade\Log::error('Draw note failed: ' . $e->getMessage() . ' Code: ' . $e->getCode() . ' Trace: ' . $e->getTraceAsString());
                if ($e->getCode() === 400) {
                    return $this->error($e->getMessage());
                }
                return $this->error('抽取纸条时发生内部错误');
            }
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        } catch (\Exception $e) {
            \think\facade\Log::error('NoteController draw method error: ' . $e->getMessage() . ' Trace: ' . $e->getTraceAsString());
            return $this->error('处理抽取请求时发生错误');
        }
    }
    
    /**
     * 创建微信支付订单
     *
     * @param NoteDraw $noteDraw
     * @return array
     */
    protected function createWechatPayment(NoteDraw $noteDraw)
    {
        try {
            $config = [
                'app_id' => Env::get('wechat.WECHAT_PAYMENT_APPID', ''),
                'mch_id' => Env::get('wechat.WECHAT_PAYMENT_MCH_ID', ''),
                'key' => Env::get('wechat.WECHAT_PAYMENT_KEY', ''),
                'notify_url' => Env::get('wechat.WECHAT_PAYMENT_NOTIFY_URL', ''),
                // 'sandbox' => (bool) Env::get('wechat.payment_sandbox', false),
            ];
            
            \think\facade\Log::info('微信支付配置信息：' . json_encode([
                'app_id' => $config['app_id'],
                'mch_id' => $config['mch_id'],
                'key_exists' => !empty($config['key']),
                'notify_url' => $config['notify_url'],
                'order_id' => $noteDraw->order_id,
                'amount' => $noteDraw->amount,
            ], JSON_UNESCAPED_UNICODE));
            
            if (empty($config['app_id']) || empty($config['mch_id']) || empty($config['key'])) {
                throw new \Exception('微信支付配置不完整');
            }
            
            $app = Factory::payment($config);
            
            $totalFee = intval($noteDraw->amount * 100);
            if ($totalFee <= 0) {
                throw new \Exception('支付金额必须大于0');
            }
            
            $orderData = [
                'body' => '纸条盲盒-抽取' . $noteDraw->draw_count . '张纸条',
                'out_trade_no' => $noteDraw->order_id,
                'total_fee' => $totalFee,
                'trade_type' => 'JSAPI',
                'openid' => $this->user->openid,
            ];
            
            \think\facade\Log::info('准备创建微信支付订单：' . json_encode($orderData, JSON_UNESCAPED_UNICODE));
            
            $result = $app->order->unify($orderData);
            
            \think\facade\Log::info('微信支付下单结果：' . json_encode($result, JSON_UNESCAPED_UNICODE));
            
            if ($result['return_code'] !== 'SUCCESS') {
                throw new \Exception('与微信支付通信失败: ' . $result['return_msg']);
            }
            if ($result['result_code'] !== 'SUCCESS') {
                throw new \Exception('微信支付下单失败: (' . $result['err_code'] . ') ' . $result['err_code_des']);
            }
            
            if ($orderData['trade_type'] === 'JSAPI') {
                $jssdk = $app->jssdk;
                $params = $jssdk->bridgeConfig($result['prepay_id'], false);
                \think\facade\Log::info('生成JSAPI支付参数成功');
                return $params;
            }
            
            return ['prepay_id' => $result['prepay_id']];
            
        } catch (\Throwable $e) {
            \think\facade\Log::error('创建微信支付订单失败: ' . $e->getMessage() . ' | 跟踪信息: ' . $e->getTraceAsString());
            // 不在此处直接返回错误给前端，而是抛出异常给调用者处理
            throw new \Exception('创建支付订单失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取我的纸条列表
     *
     * @OA\Get(
     *     path="/api/note/my_notes",
     *     summary="获取我的纸条列表",
     *     description="获取当前用户提交的纸条列表，分页展示",
     *     tags={"纸条"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码，默认1",
     *         required=false,
     *         @OA\Schema(type="integer", default=1)
     *     ),
     *     @OA\Parameter(
     *         name="limit",
     *         in="query",
     *         description="每页记录数，默认20",
     *         required=false,
     *         @OA\Schema(type="integer", default=20)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="获取成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200, description="状态码，200表示成功"),
     *             @OA\Property(property="msg", type="string", example="获取成功", description="提示信息"),
     *             @OA\Property(property="data", type="object", description="返回数据",
     *                 @OA\Property(property="total", type="integer", example=10, description="总记录数"),
     *                 @OA\Property(property="per_page", type="integer", example=20, description="每页数量"),
     *                 @OA\Property(property="current_page", type="integer", example=1, description="当前页码"),
     *                 @OA\Property(property="last_page", type="integer", example=1, description="最后一页页码"),
     *                 @OA\Property(property="data", type="array", description="纸条列表", 
     *                     @OA\Items(type="object",
     *                         @OA\Property(property="id", type="integer", example=1, description="纸条ID"),
     *                         @OA\Property(property="user_id", type="integer", example=1, description="发布用户ID"),
     *                         @OA\Property(property="nickname", type="string", example="张三", description="纸条上的昵称，可能与用户昵称不同"),
     *                         @OA\Property(property="avatar", type="string", example="https://example.com/avatar.jpg", description="纸条上展示的头像URL"),
     *                         @OA\Property(property="gender", type="integer", example=1, description="性别: 0-未知, 1-男, 2-女"),
     *                         @OA\Property(property="age", type="integer", example=25, description="年龄"),
     *                         @OA\Property(property="city", type="string", example="北京", description="所在城市"),
     *                         @OA\Property(property="wechat_id", type="string", example="wxid_123456", description="微信号"),
     *                         @OA\Property(property="wechat_qrcode", type="string", example="https://example.com/qr.jpg", description="微信二维码图片URL"),
     *                         @OA\Property(property="status", type="integer", example=1, description="状态: 0-待审核, 1-未抽取, 2-已抽取"),
     *                         @OA\Property(property="create_time", type="string", format="date-time", example="2023-07-15 10:00:00", description="创建时间"),
     *                         @OA\Property(property="update_time", type="string", format="date-time", example="2023-07-15 10:00:00", description="更新时间")
     *                     )
     *                 )
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function myNotes(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        // 获取分页参数
        list($page, $limit) = $this->getPaginate();
        
        // 查询用户的纸条
        $notes = Note::where('user_id', $this->user->id)
            ->order('create_time', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);
        
        
        return $this->success($notes, '获取成功');
    }
    
    
    /**
     * 获取订单状态
     *
     * @OA\Get(
     *     path="/api/note/order_status",
     *     summary="获取订单状态",
     *     description="根据订单号查询支付状态",
     *     tags={"纸条"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="order_id",
     *         in="query",
     *         description="订单号",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="获取成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="order_id", type="string", example="ND2023071512345678"),
     *                 @OA\Property(property="status", type="integer", example=1),
     *                 @OA\Property(property="status_text", type="string", example="已支付"),
     *                 @OA\Property(property="draw_type", type="integer", example=1),
     *                 @OA\Property(property="draw_count", type="integer", example=1),
     *                 @OA\Property(property="amount", type="number", format="float", example=1.00),
     *                 @OA\Property(property="pay_time", type="string", format="date-time", example="2023-07-15 11:00:00")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="msg", type="string", example="订单号不能为空"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function orderStatus(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        // 验证 order_id 是否存在且不为空
        $orderId = $request->param('order_id');
        if (empty($orderId)) {
            return $this->error('订单ID不能为空');
        }
        
        // 查询订单
        $noteDraw = NoteDraw::where('order_id', $orderId)
            ->where('user_id', $this->user->id)
            ->find();
            
        if (!$noteDraw) {
            return $this->error('订单不存在或无权访问');
        }
        
        // 准备返回数据
        $data = [
            'order_id' => $noteDraw->order_id,
            'status' => $noteDraw->status,
            'status_text' => $noteDraw->getStatusTextAttr(),
            'amount' => $noteDraw->amount,
            'draw_count' => $noteDraw->draw_count,
            'draw_type' => $noteDraw->draw_type,
            'draw_type_text' => $noteDraw->getDrawTypeTextAttr(),
            'create_time' => $noteDraw->create_time ? $noteDraw->create_time : '',
            'pay_time' => $noteDraw->pay_time ? $noteDraw->pay_time : '',
            'notes' => []
        ];
        
        // 如果已支付，加载抽到的纸条
        if ($noteDraw->status == 1) {
            // 根据抽取类型获取纸条信息
            if ($noteDraw->draw_type == 1) {
                // 单抽
                $note = $noteDraw->note;
                if ($note) {
                    $data['notes'] = [[
                        'id' => $note->id,
                        'nickname' => $note->nickname,
                        'gender' => $note->gender,
                        'age' => $note->age,
                        'city' => $note->city,
                        'wechat_id' => $note->wechat_id,
                        'avatar' => $note->avatar,
                        'wechat_qrcode' => $note->wechat_qrcode
                    ]];
                }
            } else {
                // 多抽，使用关联加载
                $noteDraw->load(['drawnNotes' => function($query) {
                    $query->field(['id', 'nickname', 'gender', 'age', 'city', 'wechat_id', 'avatar', 'wechat_qrcode']);
                }]);
                
                if ($noteDraw->drawnNotes) {
                    $notes = [];
                    foreach ($noteDraw->drawnNotes as $note) {
                        $notes[] = [
                            'id' => $note->id,
                            'nickname' => $note->nickname,
                            'gender' => $note->gender,
                            'age' => $note->age,
                            'city' => $note->city,
                            'wechat_id' => $note->wechat_id,
                            'avatar' => $note->avatar,
                            'wechat_qrcode' => $note->wechat_qrcode
                        ];
                    }
                    $data['notes'] = $notes;
                }
            }
        }
        
        return $this->success($data, '获取成功');
    }
    
    /**
     * 获取我抽取的纸条
     *
     * @OA\Get(
     *     path="/api/note/my_notes_detail",
     *     summary="获取我抽取的纸条",
     *     description="获取用户抽取的所有纸条详情列表，只返回纸条信息，并包含价格和抽取时间",
     *     tags={"纸条"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码，默认1",
     *         required=false,
     *         @OA\Schema(type="integer", default=1)
     *     ),
     *     @OA\Parameter(
     *         name="limit",
     *         in="query",
     *         description="每页记录数，默认10",
     *         required=false,
     *         @OA\Schema(type="integer", default=10)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="获取成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="total", type="integer", example=15, description="总记录数"),
     *                 @OA\Property(property="per_page", type="integer", example=10, description="每页数量"),
     *                 @OA\Property(property="current_page", type="integer", example=1, description="当前页码"),
     *                 @OA\Property(property="last_page", type="integer", example=2, description="最后一页页码"),
     *                 @OA\Property(property="data", type="array", 
     *                     @OA\Items(type="object",
     *                         @OA\Property(property="id", type="integer", example=20),
     *                         @OA\Property(property="nickname", type="string", example="张三"),
     *                         @OA\Property(property="gender", type="integer", example=1),
     *                         @OA\Property(property="age", type="integer", example=25),
     *                         @OA\Property(property="city", type="string", example="北京"),
     *                         @OA\Property(property="wechat_id", type="string", example="wxid_123456"),
     *                         @OA\Property(property="avatar", type="string", example="https://example.com/avatar.jpg"),
     *                         @OA\Property(property="wechat_qrcode", type="string", example="https://example.com/qrcode.jpg"),
     *                         @OA\Property(property="draw_time", type="string", format="date-time", example="2025-04-21 09:53:55", description="抽取时间"),
     *                         )
     *                 )
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function myNotesDetail(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        try {
            // 获取分页参数
            list($page, $limit) = $this->getPaginate();
            
            \think\facade\Log::info('获取我的纸条详情列表，用户ID: ' . $this->user->id . ', 页码: ' . $page . ', 每页数量: ' . $limit);
            
            // 准备返回数据
            $allNotes = [];
            $total = 0;
            
            // 获取用户所有已支付订单
            $draws = NoteDraw::where('user_id', $this->user->id)
                ->where('status', 1)
                ->order('pay_time', 'desc')
                ->select();
            
            foreach ($draws as $draw) {
                if ($draw->draw_type == 1) {
                    // 单抽
                    $note = Note::where('id', $draw->note_id)->find();
                    if ($note) {
                        $allNotes[] = [
                            'id' => $note->id,
                            'nickname' => $note->nickname,
                            'gender' => $note->gender,
                            'age' => $note->age,
                            'city' => $note->city,
                            'wechat_id' => $note->wechat_id,
                            'avatar' => $note->avatar,
                            'wechat_qrcode' => $note->wechat_qrcode,
                            'draw_time' => $draw->pay_time ? $draw->pay_time : '',
                        ];
                    }
                } else {
                    // 多抽，从中间表查询
                    $noteIds = Db::name('note_draw_items')
                        ->where('draw_id', $draw->id)
                        ->column('note_id');
                    
                    if (!empty($noteIds)) {
                        $notes = Note::whereIn('id', $noteIds)->select();
                        foreach ($notes as $note) {
                            $allNotes[] = [
                                'id' => $note->id,
                                'nickname' => $note->nickname,
                                'gender' => $note->gender,
                                'age' => $note->age,
                                'city' => $note->city,
                                'wechat_id' => $note->wechat_id,
                                'avatar' => $note->avatar,
                                'wechat_qrcode' => $note->wechat_qrcode,
                                'draw_time' => $draw->pay_time ? $draw->pay_time : '',
                            ];
                        }
                    }
                }
            }
            
            // 记录总数量
            $total = count($allNotes);
            
            // 手动分页
            $offset = ($page - 1) * $limit;
            $paginatedNotes = array_slice($allNotes, $offset, $limit);
            
            // 构建分页结果
            $result = [
                'total' => $total,
                'per_page' => $limit,
                'current_page' => $page,
                'last_page' => ceil($total / $limit),
                'data' => $paginatedNotes
            ];
            
            \think\facade\Log::info('获取纸条详情成功，总记录数: ' . $total . ', 当前页: ' . $page . ', 每页: ' . $limit);
            
            return $this->success($result, '获取成功');
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取纸条详情异常: ' . $e->getMessage() . ' | 跟踪: ' . $e->getTraceAsString());
            return $this->error('获取纸条详情失败: ' . $e->getMessage());
        }
    }
} 